<script setup>
import {ref, computed, onMounted, onUnmounted} from 'vue'
import ComAffix from "@/components/ComAffix.vue";
import router from "@/router/index.js";
import {useUserInfoStore, useUserStore} from "@/stores/index.js";
import {postLike} from '@/utiles/userInfo.js'
import {humanizeNumber} from "@/utiles/format.js";
import {getPostListService} from "@/api/post.js";

const userInfoStore = useUserInfoStore()
const userStore = useUserStore()
const pageNum = ref(1)
const pageSize = ref(9)
const hasMore = ref(true)
const isLoading = ref(false)
const isRefreshing = ref(false)
const pullDistance = ref(0)
const posts = ref([
])
const sleep = (ms) => {
  return new Promise(resolve => setTimeout(resolve, ms));
};

const  getPosts = async () => {
  if (isLoading.value || !hasMore.value) return;
  isLoading.value = true;
  const userId = userStore.user.id;
  try {
    const res = await getPostListService(pageNum.value,pageSize.value,userId)
    if(posts.value.length>0){
      await sleep(500);
    }
    if (isRefreshing.value) {
      posts.value = res.data.data;
    } else {
      posts.value = [...posts.value, ...res.data.data];
    }
    hasMore.value = res.data.data.length >= pageSize.value;
    pageNum.value++;
  } finally {
    isLoading.value = false;
    isRefreshing.value = false;
    pullDistance.value = 0;
  }
}
getPosts()

const handleScroll = () => {
  const { scrollTop, scrollHeight, clientHeight } = document.documentElement;
  if (scrollTop + clientHeight >= scrollHeight - 50 && !isLoading.value) {
    getPosts()
  }
};

// 在挂载时添加监听
onMounted(() => {
  window.addEventListener('scroll', handleScroll);
});

// 卸载时移除监听
onUnmounted(() => {
  window.removeEventListener('scroll', handleScroll);
});


// 将帖子分配到三列
const columnPosts = computed(() => {
  const columns = [[], [], []]
  posts.value.forEach((post, index) => {
    columns[index % 3].push(post)
  })
  return columns
})


//跳转至post页
const viewPost = (post) => {
  router.push({
    name: 'Post',
    params: {
      id: post.id,
    }
  })
}
//跳转至tag页
const viewTag = (tagName) => {
  router.push({
    name: 'SearchTag',
    query: {
      tagName: tagName
    }
  })
}

const handlePostLike = (id, sign,post) => {
  postLike(id,sign,post)
}
</script>

<template>
  <div class="main">
    <el-affix :offset="0">
      <ComAffix></ComAffix>
    </el-affix>
    <div class="w" @scroll="handleScroll">
      <div class="post-list-container">
        <!-- 三列布局 -->
        <div class="post-column" v-for="(column, index) in columnPosts" :key="index">
          <div
            class="post-card"
            v-for="post in column"
            :key="post.id"
          >
            <!-- 封面图片 -->
            <el-image v-if="post.cover" class="post-cover" :src="post.cover" :fit="'contain'">
            </el-image>

            <!-- 帖子内容 -->
            <div class="post-content">
              <!-- 标题和标签 -->
              <h3 class="post-title" @click="viewPost(post)" style="cursor: pointer">{{ post.title }}</h3>

              <!-- 文字内容 (限制3行) -->
              <p class="post-text" v-html="post.content"></p>

              <div class="post-tags">
                <svg class="icon" aria-hidden="true">
                  <use xlink:href="#icon-tubiao_biaoqian"></use>
                </svg>
                <span v-for="(tag, tagIndex) in post.tags.slice(0,5)"
                      :key="tagIndex"  class="tag-item"
                      @click="viewTag(tag)"
                      style="cursor: pointer"
                >
                   {{ tag }}
                </span>
              </div>
              <!-- 作者信息 -->
              <div class="author-info">
                <el-avatar
                  :size="32"
                  :src="post.author.avatar"
                  class="author-avatar"
                />
                <span class="author-name"><router-link  :to="{ name: 'OtherUser', query: { userId: post.author.id} }">{{ post.author.nickname}}</router-link></span>

                <span class="like">
                  <svg class="icon" aria-hidden="true" @click="handlePostLike(post.id,0,post)"
                   v-if="!userInfoStore.postLike.includes(post.id)">
                    <use xlink:href="#icon-dianzan"></use>
                  </svg>
                  <svg class="icon" aria-hidden="true" @click="handlePostLike(post.id,1,post)" v-else>
                    <use xlink:href="#icon-dianzanshoucang"></use>
                  </svg>
                  <span class="number">{{humanizeNumber( post.likeCount)}}</span>
                </span>

              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div v-if="isLoading" class="loading-tip">加载中...</div>
    <div v-if="!hasMore" class="nomore-tip">没有更多内容了</div>
  </div>
</template>
<style scoped lang="scss">
.main{
  background-color: #f6f3f3;
}
.w{
  width: 1000px;
  margin: 0 auto;
}
.post-list-container {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 24px;
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.post-column {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

a {
  text-decoration: none;
  cursor: pointer;
  color: #636363;
}

.post-card {
  background: #fff;
  border-radius: 8px; // 增大圆角
  box-shadow: 0 2px 8px rgba(0,0,0,0.08); // 初始轻微阴影
  overflow: hidden;
  transition: all 0.3s cubic-bezier(0.25, 0.8, 0.25, 1); // 平滑过渡曲线
  &:hover {
    transform: translateY(-8px) scale(1.01); // 上移并轻微放大
    filter: brightness(0.8); // 轻微变暗
  }

  .post-cover {
    width: 100%;
    border-radius: 5px 5px 0 0;
  }

  .post-content {
    padding: 12px 15px;

    .post-title {
      font-size: 18px;
      line-height: 1.4;
      color: #333;
    }
    .post-text {
      display: block; /* 移除弹性盒布局 */
      color: #666;
      font-size: 15px;
      line-height: 1.5;
      margin: 0 0 16px;
      display: -webkit-box;
      -webkit-box-orient: vertical;
      -webkit-line-clamp: 3;
      overflow: hidden;
    }
    :deep(.post-text) img {
      width: 200px;
    }

    .post-tags {
      display: flex;
      flex-wrap: wrap;
      gap: 8px;
      padding-bottom: 10px;
      border-bottom: 1px solid #dad8d8;
      .icon{
        height: 20px;
        width: 20px;
        margin-right: 5px;
      }
      .tag-item {
        font-size: 14px;
        color: #646464;
        font-family: '华文楷体', serif;
      }
    }


    .author-info {
      display: flex;
      align-items: center;
      gap: 8px;
      margin-top: 10px;
      .author-avatar {
        flex-shrink: 0;
      }

      .author-name {
        flex: 1;
        font-size: 14px;
        color: #333;
        max-width: 150px;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
        font-family: 'serif','华文中宋';
      }

      .like{
        font-size: 15px;
        position: relative;
        margin-left: 12px;
        .icon{
          width: 30px;
          height: 30px;
          color: #646464;
        }

        .number{
          position: absolute;
          top: 6px;
        }
      }
    }

  }

}
.loading-tip, .nomore-tip {
  text-align: center;
  padding: 20px;
  color: #666;
}
</style>
